<?php
/**
 * Created by PhpStorm.
 * User: HuangLuSen
 * Date: 2017/11/23
 * Time: 13:48
 */

namespace app\common\controller;

use app\admin\logic\User;
use app\admin\model\Users;
use app\common\logic\Login;
use think\Cache;
use think\Controller;
use app\wechat\traits\Wechat;
use think\Db;

/**
 * 公共基类
 * 功能特性：
 */
class Base extends Controller
{
    use Wechat;
    protected function _initialize()
    {
        parent::_initialize();
    }
    /**
     * 向微信服务器发起用户信息请求
     * @param $callbackurl 会跳地址
     * @internal
     */
    public function login($callbackurl)
    {
        //地址带code的跳转?code=071K3uYu1SzDmd0p0u0v1ssxYu1K3uYC&amp;state=0262505234c68bcd2f7dbdd7433028e5
        if (!empty(session('user_weixin'))) $this->redirect(url('index/login/index', ['url' => urlencode($callbackurl)]));
        if (!request()->param('code')) {
            session('url', $callbackurl);
            self::getInstance()->oauth->redirect($callbackurl)->send(); //发起网页授权请求
        } elseif (request()->param('code')) {
            $oauth = self::getInstance()->oauth;//获取微信回掉回来的东西
            $user = $oauth->user()->toArray();
            foreach ($user['original'] as $key => $value) {
                $user[$key] = $value;
            }
            unset($user['original']);
            unset($user['token']);
            session('user_weixin', $user);
            $data = Db::name('users')->where('openid', $user['id'])->find();
            if (!empty($data)) {
                Login::auto_login(['username'=>$data['username'],'id'=>$data['id']]);
            }
            $this->redirect(session('url'));
        }
    }

}